local desc_tshu8 = [[
  # 天书乱斗模式简介

  PVP模式，支持2~10人游玩

  胜负规则同身份模式，起始手牌多摸一张，9人局内奸+1，10人局反贼+1
  ___

  游戏开始所有玩家随机获得白板武将牌，然后由主公优先选择获得至多2个技能，主公选择完其他玩家各选择获得2个技能

  每少选一个技能体力上限+1且起始手牌+2，至少选择获得1个技能

  若为5人以上局，主公额外选择获得一个主公技和1点体力上限
  
  （开启自由选将改为额外获得1个技能，开启副将改为额外获得2个技能与3点体力上限）

  技能池取决于开启武将，技能库数量取决于选将框数量
]]

local ban_skills = {
  "fenyong", "danggu", -- 弱智技能
  "duorui", "quanfeng", "zhongliu", "yongdi", "chuanwu", "tuogu", "zeyue", "n_dianlun", "xiaode" -- 和武将牌上的技能有关的
}
--黑名单
local blacklist = {"mouxusheng","jbsao__wuyaowang","ty__tengfanglan","jbs_sairen","luyi","dingfuren","zuoci","os__zhaoxiang","zhaoxiang","ol_ex__zuoci","buqun__ailing"}


local U = require "packages/utility/utility"

local tshu8_getLogic = function()
  local tshu8_logic = GameLogic:subclass("tshu8_logic") ---@class GameLogic

  function tshu8_logic:initialize(room)
    GameLogic.initialize(self, room)
    self.role_table = {
      { "lord" },
      { "lord", "rebel" },
      { "lord", "rebel", "renegade" },
      { "lord", "loyalist", "rebel", "renegade" },
      { "lord", "loyalist", "rebel", "rebel", "renegade" },
      { "lord", "loyalist", "rebel", "rebel", "rebel", "renegade" },
      { "lord", "loyalist", "loyalist", "rebel", "rebel", "rebel", "renegade" },
      { "lord", "loyalist", "loyalist", "rebel", "rebel", "rebel", "rebel", "renegade" },
      { "lord", "loyalist", "loyalist", "rebel", "rebel", "rebel", "rebel", "renegade","renegade" },
      { "lord", "loyalist", "loyalist", "rebel", "rebel", "rebel", "rebel", "rebel", "renegade" ,"renegade"},
    }

  end

  function tshu8_logic:assignRoles()
    local room = self.room
    local n = #room.players
    local roles = self.role_table[n]
    table.shuffle(roles)

      --默认主反模式
      for i = 1, n do
        local p = room.players[i]
        p.role = roles[i]
        if p.role == "lord" then
          p.role_shown = true
          room:broadcastProperty(p, "role")
        else
          room:notifyProperty(p, p, "role")
        end
      end
  end

  function tshu8_logic:chooseGenerals()
    local room = self.room ---@type Room

    local lord = room:getLord()
    room.current = lord
    local players = room.players
    local num = 2
    local morehp = 0
    if room.settings.enableFreeAssign then
      --room:doBroadcastNotify("ShowToast", "已开启自由选将，获得技能+1。")
      --room:delay(500)
      num = num + 1
    end
    if room.settings.enableDeputy then
      --room:doBroadcastNotify("ShowToast", "已开启副将按钮，获得技能+2,血量上限+3。")
      --room:delay(500)
      num = num + 2
      morehp = 3
    end
    --武将
    for _, p in ipairs(players) do
      local gens = room:getNGenerals(room.settings.generalNum)
      p.request_data = json.encode({ gens, 1 })
      p.default_reply = gens[1]
      room:returnToGeneralPile(gens)
    end
    room:doBroadcastNotify("ShowToast","选择自己的武将形象（决定性别）。")
    room:delay(500)
    room:doBroadcastRequest("AskForGeneral", room.players)
    for _, p in ipairs(room.players) do
      local general
      if p.general == "" and p.reply_ready then
       general = json.decode(p.client_reply)[1]
      else
        general = p.default_reply
      end
      room:setPlayerGeneral(p, general, true)
      room:broadcastProperty(p, "general")
      local noto_rm = table.filter(p.player_skills, function(s)
        return not s.attached_equip  and s.name[#s.name] ~= "&" -- 不是装备技和按钮的全图图了
      end)
      room:handleAddLoseSkills(p, table.concat(table.map(noto_rm, function(s) return "-" .. s.name end), "|"), nil, true)
      room:setPlayerProperty(p, "shield", 0)
      room:setPlayerProperty(p, "kingdom","god")
    end
    local skill_num = math.min(30,2*room.settings.generalNum) -- 技能池数量由选将数决定
    local total = math.floor(skill_num * (1+#room.players))
    local skill_pool, general_pool = {}, {}
    local lordskill_pool, lordgeneral_pool = {}, {}
    local all_generals = room.general_pile -- Fk:getAllGenerals() -- replace Engine:getGeneralsRandomly
    --黑名单
    for _, g in ipairs(blacklist) do
      table.removeOne(all_generals,g)
    end
    local lords = room:findGenerals(function(g)
      return table.contains(Fk.lords, g)
    end, 10)
    local i = 0
    for _ = 1, 999 do
      local general = Fk.generals[table.random(all_generals)] ---@type General
      local skills = general:getSkillNameList()
      local skill = table.random(skills) ---@type string
      local des = Fk:translate(":" .. skill, "zh_CN")
      if not table.contains(ban_skills, skill) and not table.contains(skill_pool, skill) and not Fk.skills[skill].lordSkill then
        i = i + 1
        table.insert(skill_pool, skill)
        table.insert(general_pool, general.name)
        if i == total then break end
      end
    end
    if i < total then
      room:doBroadcastNotify("ShowToast", "技能池不够，游戏结束。")
      room:gameOver("")
    end
    
    local h = 0
    for __ = 1, 999 do
      if #room.players < 5 then break end
      local general = Fk.generals[table.random(lords)] ---@type General
      local skills = general:getSkillNameList()
      local skill = table.random(skills) ---@type string
      local lord_skill = table.find(general.skills, function(s)
        return s.lordSkill
      end)
      if lord_skill and not table.contains(lordskill_pool, lord_skill.name) then
        h = h + 1
        table.insert(lordskill_pool,lord_skill.name)
        table.insert(lordgeneral_pool, general.name)
        if h == 5 then break end
      end
    end
    
    ------------主公普通技能---------
    local lskills = table.slice(skill_pool, 1,skill_num+ 1)
    local lgenerals = table.slice(general_pool,1, total + 1)
    lord.request_data = json.encode({
      path = "packages/utility/qml/ChooseSkillBox.qml",
      data = {
        lskills,1, num, "#tshu8-choose:::" .. tostring(num),lgenerals, true
      },
    })
    lord.default_reply = table.random(lskills, num)

    room:doBroadcastNotify("ShowToast", "等待主公选择技能。")
    room:doBroadcastRequest("CustomDialog",{lord})
    room:notifyMoveFocus({lord}, "天书技能")

    if not lord then return end
    local choice = lord.reply_ready and json.decode(lord.client_reply) or lord.default_reply
    local hp = num - #choice
    local mark = {}
    for _, sk in ipairs({choice}) do
      table.forEach(sk, function(s)  table.insertIfNeed(mark,s) end)
    end
    --room:handleAddLoseSkills(lord, table.concat(choice, "|"), nil)
    room:setPlayerMark(lord, "@[tshu__tianshu]",mark)
    lord.default_reply = ""
    room:setPlayerProperty(lord, "maxHp",3 + hp + morehp)
    room:setPlayerProperty(lord, "hp",3 + hp + morehp)


    -------------------主公技------------
    if #room.players >= 1 then
      if #lordskill_pool >= 1 then
      local all = #lordskill_pool + 1
      local lorskills = table.slice(lordskill_pool,1,all)
      local lorgenerals = table.slice(lordgeneral_pool,1,all)
      lord.request_data = json.encode({
      path = "packages/utility/qml/ChooseSkillBox.qml",
      data = {
        lorskills,1,1, "#tshu8-lord-choose:::" .. tostring(1),lorgenerals, true
        },
      })
      lord.default_reply = table.random(lorskills,1)

      room:doBroadcastNotify("ShowToast", "等待主公选择主公技。")
      room:doBroadcastRequest("CustomDialog",{lord})
      room:notifyMoveFocus({lord}, "主公技")
      local choicelord = lord.reply_ready and json.decode(lord.client_reply) or lord.default_reply
      for _, sk in ipairs({choicelord}) do
        table.forEach(sk, function(s)  table.insertIfNeed(mark,s) end)
      end
      --room:handleAddLoseSkills(lord, table.concat(choicelord, "|"), nil)
      room:setPlayerMark(lord, "@[tshu__tianshu]", mark)
      lord.default_reply = ""
      end
      room:setPlayerProperty(lord, "maxHp",lord.maxHp + 1)
      room:setPlayerProperty(lord, "hp",lord.hp + 1 )
      
    end
    room:askForChooseKingdom({lord})
    room:broadcastProperty(lord, "kingdom")


    ------------其他玩家技能-----------
    local n = 1
    for k, p in ipairs(room:getOtherPlayers(lord)) do
      --dbg()
      n = n + 1
      k =n + 1
      local skills2, generals2
      skills2 = table.slice(skill_pool, skill_num * (k - 1) + 1 , skill_num * k + 1)
      generals2 = table.slice(general_pool, skill_num * (k - 1) + 1 , skill_num * k + 1)
      p.request_data = json.encode({
        path = "packages/utility/qml/ChooseSkillBox.qml",
        data = {
          skills2,1, num, "#tshu8-choose:::" .. tostring(num), generals2, true
        },
      })
      p.default_reply = table.random(skills2,num)
    end

    room:doBroadcastNotify("ShowToast", "其他玩家选择技能。")
    room:doBroadcastRequest("CustomDialog",room:getOtherPlayers(lord))
    room:notifyMoveFocus(room:getOtherPlayers(lord), "天书技能")
    for _, p in ipairs(room:getOtherPlayers(lord)) do
      local choice2 = p.reply_ready and json.decode(p.client_reply) or p.default_reply
      local hp2 = num - #choice2
      local mark2 = {}
      for _, sk in ipairs({choice2}) do
        table.forEach(sk, function(s)  table.insertIfNeed(mark2,s) end)
      end
      --room:handleAddLoseSkills(p, table.concat(choice2, "|"), nil)
      room:setPlayerMark(p, "@[tshu__tianshu]",mark2)
      p.default_reply = ""
      room:setPlayerProperty(p, "maxHp",3 + hp2 + morehp)
      room:setPlayerProperty(p, "hp",3 + hp2 + morehp)
    end
    room:askForChooseKingdom(room:getOtherPlayers(lord))
    for _, p in ipairs(room:getOtherPlayers(lord)) do
      room:broadcastProperty(p, "kingdom")
    end
  end

  function tshu8_logic:broadcastGeneral()
    
  end
  function tshu8_logic:attachSkillToPlayers()
    local room = self.room
    for _, p in ipairs(room.players) do
      local mark = type(p:getTableMark("@[tshu__tianshu]") == "table") and p:getTableMark("@[tshu__tianshu]") or {}
      if #mark > 0 then
        room:handleAddLoseSkills(p, table.concat(mark, "|"), nil,false)
      end
    end
  end

  return tshu8_logic
end

local tshu8_rule = fk.CreateTriggerSkill{
  name = "#tshu8_rule",
  priority = 0.001,
  refresh_events = {fk.DrawInitialCards,fk.GamePrepared},
  can_refresh = function(self, event, target, player, data)
    return  target == player or event == fk.GamePrepared
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.DrawInitialCards then
      local num = 2
      if room.settings.enableFreeAssign then
        num = num + 1
      end
      if room.settings.enableDeputy then
        num = num + 2
      end
      if player.role == "lord" and #room.players >= 5 then
        num = num + 1
      end
        data.num = data.num + 1 + 2*math.max(0,(num - #player:getTableMark("@[tshu__tianshu]")))
    end
  end,
}
Fk:addSkill(tshu8_rule)
local tshu8_mode = fk.CreateGameMode{
  name = "tshu8_mode",
  minPlayer = 2,
  maxPlayer = 10,
  main_mode = "role_mode",
  rule = tshu8_rule,
  logic = tshu8_getLogic,
  surrender_func = function(self, playedTime)
    return Fk.game_modes["aaa_role_mode"].surrenderFunc(self, playedTime)
  end,
}

Fk:loadTranslationTable{
  ["tshu8_mode"] = "无尽天书(PVP)",
  ["#tshu8-choose"] = "请选择至多%arg个技能，每少选一个体力上限+1且起始手牌+2",
  ["#tshu8-lord-choose"] = "请选择1个主公技",
  [":tshu8_mode"] = desc_tshu8,

}



return tshu8_mode
